package com.weigang.webservice.interceptor;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import com.weigang.webservice.utils.Constant;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;


public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    private static final String USER_NAME = "admin";
    private static final String USER_PASSWORD = "123456";

    public AuthInterceptor() {
        super("pre-protocol");
    }

    public void handleMessage(SoapMessage message) throws Fault {
        Header header = message.getHeader(new QName(Constant.NAMESPACE,"login"));
        if (header != null) {
            Element element = (Element)header.getObject();
            String username = element.getElementsByTagName("username").item(0).getTextContent();
            String password = element.getElementsByTagName("password").item(0).getTextContent();
            if (username.equals(USER_NAME) && password.equals(USER_PASSWORD)) {
                System.out.println("通过拦截器...");
                return;
            }
        }

        System.out.println("没有通过拦截器");
        throw new Fault(new RuntimeException("用户名或密码不正确"));
    }
}
